# coding=utf-8
# 建立MySQL库 存储ip
# 将user password 修改 

import time, sched  
import urllib.request
import mysql.connector
import CheckProxy

# 连接服务器   验证IP
def verificationIPArr(ww):
    conn = mysql.connector.connect(user='root', password='zhanhua', database='ipDatabase')
    cursor = conn.cursor()
    
    for ipStr in ww:
        if len(ipStr)>0:
            isValid = CheckProxy.check_http_proxy(ipStr)
            if isValid:
                cursor.execute("SELECT * FROM ipList WHERE ip=\'"+ipStr+"\';")
                linesLen = len(cursor.fetchall())
                if linesLen<=0:                
                    # 插入数据
                    cursor.execute('insert into ipList ( ip, usedNum, lastUsedTime) values (%s, %s, %s);', ((ipStr),0,0))
                    conn.commit()
    
    cursor.close()    
    conn.close()
          

#被调度触发的函数  
def event_func():  
    # print("Current Time:", time.strftime("%y-%m-%d %H:%M:%S")) 
    response = urllib.request.urlopen('http://www.fldd.cn/api.asp?key=20160617162921076&getnum=10&filter=0&area=1&proxytype=0')
    buff = response.read()
    #显示
    html = str(buff.decode("utf8"))
    response.close()

    ww = (html.split('\r\n'))
    verificationIPArr(ww)

  
def run_function():  
    #初始化sched模块的scheduler类  
    s = sched.scheduler(time.time, time.sleep)  
    #设置一个调度,因为time.sleep()的时间是一秒,所以timer的间隔时间就是sleep的时间,加上enter的第一个参数  
    s.enter(0, 2, event_func)  
    s.run()  
  
def timer1():  
    while True:  
        #sched模块不是循环的，一次调度被执行后就Over了，如果想再执行，可以使用while循环的方式不停的调用该方法  
        time.sleep(60)  
        run_function()  
  
if __name__ == "__main__":  
    timer1() 
    # run_function()  
    # event_func()